<script lang="ts" setup>
import { ref } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
// 是否可以多选
const multiple = ref(false)
// 当前上传文件数量
const fileCount = ref(0)

const props = defineProps({
  // 文件数量
  count: {
    type: Number,
    required: true
  },
  // 文件上传检查回调
  checkHandle: {
    type: Function
  },
  // 文件变动回调
  fileHandle: {
    type: Function,
    required: true
  },
  // 文件回显
  fileList: {
    type: Array as () => UploadUserFile[],
    required: true
  }
})

// 如果是多张图片，可以多选
if (props.count > 1) {
  multiple.value = true
}

// 删除回调
const handleRemove = (file: UploadFile) => {
  const index = props.fileList.findIndex((item) => item.uid === file.uid)
  if (index !== -1) {
    props.fileList.splice(index, 1)
  }
}

// 查看回调
const handlePreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

// 下载回调
const handleDownload = (file: UploadFile) => {
  console.log(file)
}

// 文件状态改变回调
const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // 放入文件列表
  props.fileHandle(uploadFiles)
  // 更新文件数量
  fileCount.value = uploadFiles.length
  // 回调检查
  if (props.checkHandle) {
    return props.checkHandle()
  }
  return false
}
</script>
<template>
  <div>
    <el-upload
      :file-list="props.fileList"
      action="#"
      :limit="props.count"
      list-type="picture-card"
      :auto-upload="false"
      :multiple="multiple"
      :on-change="handleChange"
      :class="fileCount === props.count ? 'hide_box' : ''"
    >
      <el-icon><Plus /></el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleDownload(file)"
            >
              <el-icon><Download /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon><Delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <!-- 图片方法查看显示 -->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<style scoped>
.hide_box :deep() .el-upload--picture-card {
  display: none;
}
</style>
